package com.safx.selenium;

import org.apache.log4j.Logger;

import com.safx.entity.env.Environment;
import com.thoughtworks.selenium.BrowserConfigurationOptions;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

/**
 * 
 * <b>产生selenium对象</b>
 * 
 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-7
 */
public class SeleniumX {
	private static boolean isSeleniumStart = false;
	static Logger logger = Logger.getLogger(SeleniumX.class);
	// 单例模式
	private static Selenium selenium = null;
	private static Environment environment = Environment.getInstance();

	private SeleniumX() {

	}

	// singleton
	public static synchronized Selenium getInstance() {
		if (null == selenium) {
			selenium = new DefaultSelenium(environment.getConfig().getHost(), environment.getConfig().getPort(), environment.getConfig().getBrowser(), environment.getConfig().getBaseUrl());
			logger.info("New DeafaultSelenium:"+environment.getConfig().getHost()+ "|"+environment.getConfig().getPort()+"|"+environment.getConfig().getBaseUrl());
		}
		return selenium;
	}

	/**
	 * 
	 * <b> 启动selenium服务器</b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	public static void startSelenium() {
		if (null == selenium) {
			getInstance();
		}
		logger.info(">>>>>>>>>>>>>>> new selenium session start.");
		BrowserConfigurationOptions bco = new BrowserConfigurationOptions();
		selenium.start(bco.setCommandLineFlags("--disable-web-security"));
		selenium.setTimeout("" + 90000);
		selenium.windowMaximize();
		selenium.windowFocus();
		selenium.useXpathLibrary("javascript-xpath");
		isSeleniumStart = true;
	}

	/**
	 * 
	 * <b> 关闭selenium服务器</b>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-6-9
	 */
	public static void stopSelenium() {
		if (isSeleniumStart == true) {
			selenium.close();
			selenium.stop();
			logger.info("<<<<<<<<<<<<<<< stop the selenium session.");
			isSeleniumStart = false;
		}
	}
}
